
layui.config({
    base: CXL.ctxPath + '/layuiadmin/' //静态资源所在路径
}).extend({
    index: 'lib/index' //主入口模块
}).use(['index', 'table', 'laydate', 'echarts'], function () {
    var admin = layui.admin;
    var table = layui.table;
    var form = layui.form;
    var laydate = layui.laydate;
    var $ = layui.$;


    //数据图的参数
    var apartData = null;
    var apartchart = document.getElementById('apartChart');
    var apartechart = null;

//执行方法
    initPage();


    //函数区域
    function initPage() {
        initMaterialSelect();
        apartechart = echarts.init(apartchart);
        updateApartChartData();
        $(document).ready(function () {
            apartechart.resize();
        })
        window.addEventListener("resize", function () {
            apartechart.resize();
        });
    }

//初始化上料仓选择
    function initMaterialSelect() {
        let materialSelect1 = $('#materialTypeSelect1');
        getMaterialForInput(materialSelect1, form);
    }

    /**
     *    更新图表数据
     */
    function updateApartChartData(postData) {
        $.ajax({
            url: CXL.ctxPath + "/semiautomatic/apartrecord/getMaterialAndCountByParams",
            type: "POST",
            data: postData,
            dataType: "json",
            success: function (res) {
                if (res.success) {
                    apartData = res.obj;
                    let sOption = getChartOption();
                    apartechart.hideLoading();
                    apartechart.setOption(sOption,{notMerge:true});
                } else {
                    CXL.error(res.msg);
                }
            },
            fail: function () {
                CXL.error("网络错误！");
            }
        });

    }

    //获取图表参数
    function getChartOption() {
        //数据表参数
        let faultOption = {
            color: ['#1d9dff', '#006cff', '#60cda0', '#ed8884', '#8b78f6', '#3a91d2', '#06a0ab', '#86c9f4'],
            tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b} : {c} ({d}%)'
            },
            // legend: {
            //     left: 'center',
            //     top: 'bottom',
            //     data: ['小车变频故障', '大车变频故障', '小车热继故障', '大车热继故障', '起升变频故障', '抓斗钢丝绳脱槽故障','主起升重锤故障', '其它'],
            //     textStyle: {
            //         color: '#fff'
            //     }
            // },
            series: [
                {
                    name: '物料类型',
                    type: 'pie',
                    label: {
                        show: true,
                        color: '#ff0'
                    },
                    emphasis: {
                        label: {
                            show: true,

                        }
                    },
                    data: apartData
                }
            ]
        };
        return faultOption;
    }

    /**
     * 表格参数
     */
    var Page = {
        tableId: 'plan-table',
        url: CXL.ctxPath + '/semiautomatic/apartrecord/datagrid',
        toolbar: '#plan-toolbar',
        where: {field: 'endTime', order: 'desc'},
        initColumn: function () {
            return [[
                {type: 'numbers'}
                , {field: 'id', title: 'ID', hide: true, width: 120}
                , {field: 'craneId', title: '天车编号', width: 120}
                , {
                    field: 'workType', title: '任务类型', width: 120, templet: function (d) {
                        if (d.workType == "pour") {
                            res = "倒料"
                        } else if (d.workType == "dump") {
                            res = "放料"
                        } else if (d.workType == "move") {
                            res = "移动"
                        } else {
                            res = "上料"
                        }
                        return res;
                    }
                }
                , {field: 'materialName', title: '物料类型', width: 120}
                , {field: 'outputName', title: '上料仓', width: 120}
                , {
                    field: 'beginTime',
                    title: '开始时间',
                    width: 180,
                    templet: '<div>{{ layui.laytpl.toDateString(d.beginTime) }}</div>'
                }
                , {
                    field: 'endTime',
                    title: '完成时间',
                    width: 180,
                    templet: '<div>{{ layui.laytpl.toDateString(d.endTime) }}</div>'
                }
            ]];
        },
    };


    /**
     * 页面查询
     */
    Page.searchAction = function () {
        let queryData = {};
        //查询字段
        if ($("#craneidinput").val() != 0) {
            queryData['craneId_begin'] = parseInt($("#craneidinput").val());
            queryData['craneId_end'] = parseInt($("#craneidinput").val());
        } else {
            queryData['craneId_begin'] = 1;
            queryData['craneId_end'] = 4;
        }
        queryData['endTime_begin'] = $("#timeBegin").val();
        queryData['endTime_end'] = $("#timeEnd").val();
        queryData['workType'] = $("#tasktypeinput").val();
        var materialId = parseInt($("#materialTypeSelect1").val());

        // var outputId =   parseInt($("#outportStoreSelect1").val());
        // queryData['materialId'] = parseInt($("#materialTypeSelect1").val());

        // console.log(materialId);
        if(!isNaN(materialId)){
            queryData['materialId_begin'] = materialId;
            queryData['materialId_end'] = materialId;
        } else {
            queryData['materialId_begin'] = 0;
            queryData['materialId_end'] =100;
        }

        // if(outputId !=0){
        //     queryData['outputId_begin'] = outputId;
        //     queryData['outputId_end'] = outputId;
        // } else {
        //     queryData['outputId_begin'] = 0;
        //     queryData['outputId_end'] = 1000;
        // }
        // queryData['endTime_end'] = $("#timeEnd").val();
        // //排序字段
        // queryData['field'] = 'endTime';
        // queryData['order'] = 'desc';


        let postData = {};
        postData['craneId'] = $("#craneidinput").val();
        postData['beginTime'] = $("#timeBegin").val();
        postData['endTime'] = $("#timeEnd").val();
        postData['workType'] = $("#tasktypeinput").val();
        updateApartChartData(postData);
        // console.log(queryData);
        table.reload(Page.tableId, {page: {curr: 1}, where: queryData});
    }


    /**
     * 页面查询条件的重置
     */
    Page.resetAction = function () {
        laydate.render({
            elem: '#timeBegin' //指定元素
            , type: 'datetime'
            , value: new Date(new Date().getTime() - 8 * 60 * 60 * 1000)
        });
        laydate.render({
            elem: '#timeEnd' //指定元素
            , type: 'datetime'
            , value: new Date()
        });
        $("#craneidinput").val(0);
        $("#tasktypeinput").val('');
        form.render();
        Page.searchAction();
    }


    /**
     * 表格的单击事件
     */
    Page.clickAction = function (obj) {

    }

    /**
     * 表格的双击事件
     */
    Page.doubleClickAction = function (obj) {

    }

    /**
     * 新增
     */
    Page.openAdd = function () {
        layer.open({
            type: 2,
            title: '新增',
            shadeClose: true,
            shade: 0.8,
            area: ['700px', '700px'],
            content: Page.addUrl,
            btn: ['确定', '取消'],
            yes: function (index, layero) {
                //点击确认触发 iframe 内容中的按钮提交
                var submit = layero.find('iframe').contents().find("#form-btn-save");
                submit.click();

                //刷新表格
                Page.searchAction();
            }
        });
    };

    /**
     * 编辑
     */
    Page.openEdit = function (data) {
        layer.open({
            type: 2,
            title: '查看',
            shadeClose: true,
            shade: 0.8,
            area: ['700px', '700px'],
            content: Page.addUrl + "?id=" + data.id,
            btn: ['确定', '取消'],
            yes: function (index, layero) {
                //点击确认触发 iframe 内容中的按钮提交
                var submit = layero.find('iframe').contents().find("#form-btn-save");
                submit.click();

                //刷新表格
                Page.searchAction();
            }
        });
    };

    /**
     * 查看
     */
    Page.openDetail = function (data) {
        var data = data.data;
        var layer = layui.layer;
        layer.open({
            type: 1,
            content: $('#openShowBox'),
            area: ['700px', '800px'], //宽高
            btn: ["确定"],
            success: function (index, layero) {

                table.render({
                    elem: '#openShowTaskDetails'
                    , height: 'full-140'
                    , page: true
                    , limit: 30
                    , autoSort: false
                    , url: Page.url + "/" + data.id
                    , page: true
                    , cols: [[ //表头
                        {field: 'id', title: 'ID', sort: true, fixed: 'left'}
                        , {
                            field: 'beginTime',
                            title: '开始时间',
                            width: 180,
                            templet: '<div>{{ layui.laytpl.toDateString(d.beginTime) }}</div>'
                        }
                        , {
                            field: 'endTime',
                            title: '完成时间',
                            width: 180,
                            templet: '<div>{{ layui.laytpl.toDateString(d.endTime) }}</div>'
                        }
                        , {field: 'materialId', title: '物料ID', width: 90}
                        , {field: 'materialName', title: '物料名称', width: 90}
                        , {field: 'weight', title: '重量', width: 90}
                    ]]
                });

            }
        });
    }

    /**
     * 查看
     */
    Page.createWork = function (data) {
        layer.confirm('是否创建该任务？', {icon: 3, title: '提示'}, function (index) {
            //do something
            $.ajax({
                url: Page.createWorkUrl + "?id=" + data.id,
                method: 'POST',
                dataType: 'JSON',
                success(res) {
                    if (res.success) {
                        layer.close(index);
                        layer.msg('创建成功', {icon: 1});
                        Page.resetAction();
                    } else {
                        layer.close(index);
                        layer.alert(res.msg, {icon: 2});
                    }
                }
            });
        });
    }


    /**
     * 表格渲染
     */
    table.render({
        elem: '#' + Page.tableId
        , url: Page.url
        , height: 'full-140'
        , page: true
        , limit: 30
        , autoSort: false
        , toolbar: Page.toolbar
        , where: Page.where
        , defaultToolbar: [],
        done: function (res, curr, count) {
            $("#total").html(count);
        }
        , cols: Page.initColumn()
    });

    /**
     * 表头工具栏
     */
    table.on('toolbar(' + Page.tableId + ')', function (obj) {
        var checkStatus = table.checkStatus(obj.config.id);
        switch (obj.event) {
            case 'doAdd':
                Page.openAdd();
                break;
        }
        ;
    });

    /**
     * 监听表格工具事件
     */
    table.on('tool(' + Page.tableId + ')', function (obj) {
        //获得当前行数据
        var data = obj.data;
        //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
        var layEvent = obj.event;

        //查看操作
        if (layEvent === 'detail') {
            Page.openDetail(obj);
        }
        //删除操作
        else if (layEvent === 'del') {
            Page.deleteAction(obj);
        }
        //编辑操作
        else if (layEvent === 'view') {
            Page.openEdit(data);
        } else if (layEvent === 'createWork') {
            Page.createWork(data);
        }
    });


    /**
     * 搜索按钮事件
     */
    $('#btnSearch').click(function () {
        Page.searchAction();
    });

    /**
     * 搜索按钮事件
     */
    $('#btnReset').click(function () {
        Page.resetAction();
    });

    //监听行单击事件
    table.on('row(' + Page.tableId + ')', function (obj) {
        Page.clickAction(obj);
    });

    //监听行双击事件
    table.on('rowDouble(' + Page.tableId + ')', function (obj) {
        Page.doubleClickAction(obj);
    });

    /**
     * 时间选择器渲染
     * 开始时间
     */
    laydate.render({
        elem: '#timeBegin' //指定元素
        , type: 'datetime'
        , value: new Date(new Date().getTime() - 8 * 60 * 60 * 1000)
    });

    /**
     * 时间选择器渲染
     * 结束时间
     */
    laydate.render({
        elem: '#timeEnd' //指定元素
        , type: 'datetime'
        , value: new Date()
    });

});
